/**
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
}

/**
 * @description 格式化时间
 * @param time
 * @param option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * @description 将url请求参数转为json格式
 * @param url
 * @returns {{}|any}
 */
export function paramObj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"').replace(/\+/g, ' ') + '"}')
}

/**
 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @returns {*}
 */
export function translateDataToTree(data) {
  const parent = data.filter(value => value.parentId === 'undefined' || value.parentId === null)
  const children = data.filter(value => value.parentId !== 'undefined' && value.parentId !== null)
  const translator = (parent, children) => {
    parent.forEach(parent => {
      children.forEach((current, index) => {
        if (current.parentId === parent.id) {
          const temp = JSON.parse(JSON.stringify(children))
          temp.splice(index, 1)
          translator([current], temp)
          typeof parent.children !== 'undefined' ? parent.children.push(current) : (parent.children = [current])
        }
      })
    })
  }
  translator(parent, children)
  return parent
}

/**
 * @description 树形结构数据转换成父子关系的数组
 * @param data
 * @returns {[]}
 */
export function translateTreeToData(data) {
  const result = []
  data.forEach(item => {
    const loop = data => {
      result.push({
        id: data.id,
        name: data.name,
        parentId: data.parentId,
      })
      const child = data.children
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i])
        }
      }
    }
    loop(item)
  })
  return result
}

/**
 * @description 10位时间戳转换
 * @param time
 * @returns {string}
 */
export function tenBitTimestamp(time) {
  const date = new Date(time * 1000)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '' + m : m
  let d = date.getDate()
  d = d < 10 ? '' + d : d
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? '0' + minute : minute
  second = second < 10 ? '0' + second : second
  return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}

/**
 * @description 13位时间戳转换
 * @param time
 * @returns {string}
 */
export function thirteenBitTimestamp(time) {
  const date = new Date(time / 1)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '' + m : m
  let d = date.getDate()
  d = d < 10 ? '' + d : d
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? '0' + minute : minute
  second = second < 10 ? '0' + second : second
  return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}

/**
 * @description 获取随机id
 * @param length
 * @returns {string}
 */
export function uuid(length = 32) {
  const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  let str = ''
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length))
  }
  return str
}

/**
 * @description m到n的随机数
 * @param m
 * @param n
 * @returns {number}
 */
export function random(m, n) {
  return Math.floor(Math.random() * (m - n) + n)
}

/**
 * @description addEventListener
 * @type {function(...[*]=)}
 */
export const on = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event && handler) {
      element.addEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * @description removeEventListener
 * @type {function(...[*]=)}
 */
export const off = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event) {
      element.removeEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * @description 数组打乱
 * @param array
 * @returns {*}
 */
export function shuffle(array) {
  let m = array.length,
    t,
    i
  while (m) {
    i = Math.floor(Math.random() * m--)
    t = array[m]
    array[m] = array[i]
    array[i] = t
  }
  return array
}

/**
 * @description 生成query字符串
 * @param obj
 * @returns {String}
 */
export function makeURLSearchParams(obj) {
  obj = ksort(obj)
  return uni.$u.queryParams(obj, false)
}

/**
 * @description 对象属性排序
 * @param obj
 * @returns {Object}
 */
export function ksort(o) {
  let sorted = {}
  let keys = Object.keys(o)
  keys.sort()
  keys.forEach(key => {
    sorted[key] = o[key]
  })
  return sorted
}

/**
 * @description 获取签名所需参数
 * @returns {Object}
 */
export function getSignInfo() {
  let x = new Date()
  const Ut = x.getTime() + x.getTimezoneOffset() * 60 * 1000
  const Sa = uuid()
  const Sb = uuid()
  return {
    Sa,
    Ut,
    Sb,
  }
}

/**
 * @description 去除文件名扩展后缀，获取文件名
 * @param {String} str 原始文件名
 * @returns {String}
 */
export function getFileName(str) {
  if (!str.includes('.')) return str
  return str.substring(0, str.lastIndexOf('.'))
}

/**
 * @description 从scene中获取query
 * @param {String} scene 参数
 */
export function getQueryFromScene(scene) {
  const op = decodeURIComponent(scene).split('&')
  const re = {}
  op.forEach(item => {
    let keyValue = item.split('=')
    re[keyValue[0]] = keyValue[1]
  })
  return re
}

/**
 * @description 转弧度
 * @param {Number} degrees
 * @returns {Number}
 */
function degreeToRadians(degrees) {
  if (isNaN(degrees)) {
    throw new Error('Must input valid number for degrees')
  }
  return degrees * 0.017453292519943295
}

/**
 * @description 根据经纬度计算距离
 * @param {Number} lon1 经度1
 * @param {Number} lat1 纬度1
 * @param {Number} lon2 经度2
 * @param {Number} lat2 纬度2
 * @param {Number} decimal 保留几位小数
 * @returns {Number} 距离
 */
export function getDistance(lon1, lat1, lon2, lat2, decimal) {
  const sine = num => Math.sin(num / 2)
  const cos = num => Math.cos(num)
  const radius = 6371
  const λ1 = degreeToRadians(lon1)
  const φ1 = degreeToRadians(lat1)
  const λ2 = degreeToRadians(lon2)
  const φ2 = degreeToRadians(lat2)
  const Δφ = φ2 - φ1
  const Δλ = λ2 - λ1
  const a = sine(Δφ) * sine(Δφ) + cos(φ1) * cos(φ2) * Math.pow(sine(Δλ), 2)
  let distance = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) * radius
  if (decimal) distance = distance.toFixed(decimal)
  return distance
}

/**
 * @description 金额格式化
 * @param {Number} number 要格式化的数字
 * @param {Number} decimals 保留几位小数
 * @param {String} decimalPoint 小数点符号
 * @param {String} thousandsSeparator 千分位符号
 * */
export function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') {
  number = `${number}`.replace(/[^0-9+-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  const sep = typeof thousandsSeparator === 'undefined' ? ',' : thousandsSeparator
  const dec = typeof decimalPoint === 'undefined' ? '.' : decimalPoint
  let s = ''
  const toFixedFix = function (n, prec) {
    const k = 10 ** prec
    return `${Math.ceil(n * k) / k}`
  }

  s = (prec ? toFixedFix(n, prec) : `${Math.round(n)}`).split('.')
  const re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, `$1${sep}$2`)
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

/**
 * @description 对比版本号
 * @param {String} v1 系统版本号
 * @param {String} v2 最低要求版本号
 * @returns {Boolean} 是否符合
 */
export function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return true
    } else if (num1 < num2) {
      return false
    }
  }

  return true
}
